package com.zzyl.nursing.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.core.redis.RedisCache;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.dto.amqp.IotMsgNotifyData;
import com.zzyl.nursing.dto.amqp.IotMsgService;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {

    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void saveDeviceData(IotMsgNotifyData data) {
        log.info("开始保存设备上报的数据");
        //获取设备id
        String deviceId = data.getHeader().getDeviceId();
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getIotId,deviceId);
        Device device = deviceService.getOne(wrapper);
        if (device == null){
            log.info("设备不存在{}",deviceId);
            return;
        }
        //解析上报数据
        List<IotMsgService> services = data.getBody().getServices();
        ArrayList<DeviceData> deviceData = new ArrayList<>();
        for (IotMsgService service : services){
            String evenTime=service.getEventTime();
            LocalDateTime localDateTime = LocalDateTimeUtil.parse(evenTime, "yyyyMMdd'T'HHmmss'Z'");
            //时区转换
            LocalDateTime eventTime= localDateTime.atZone(ZoneId.from(ZoneOffset.UTC)).
                    withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            Map<String, Object> properties = service.getProperties();
            properties.forEach((key, value) -> {
                DeviceData deviceData1 = new DeviceData();
                BeanUtils.copyProperties(device,deviceData1);
                deviceData1.setId(null);
                deviceData1.setFunctionId(key);
                deviceData1.setDataValue(value.toString());
                deviceData1.setAlarmTime(eventTime);
                deviceData.add(deviceData1);
            });
        }
        this.saveBatch(deviceData);
        //保存数据到redis中
        redisTemplate.opsForHash().put("Device_new_data",deviceId, JSONUtil.toJsonStr(deviceData));

    }

    @Override
    public List<DeviceData> listdata(DeviceDataPageReqDto dto) {
        LambdaQueryWrapper<DeviceData> wrapper = new LambdaQueryWrapper<>();
        //模糊查询设备名称
        if(StringUtils.isNotEmpty(dto.getDeviceName())){
            wrapper.eq(DeviceData::getDeviceName,dto.getDeviceName());
        }
        //精确查询功能名称
        if (StringUtils.isNotEmpty(dto.getFunctionId())) {
            wrapper.eq(DeviceData::getFunctionId, dto.getFunctionId());
        }
        //时间范围查询
        if(ObjectUtils.isNotEmpty(dto.getStartTime()) && ObjectUtils.isNotEmpty(dto.getEndTime())){
            wrapper.between(DeviceData::getAlarmTime,dto.getStartTime(),dto.getEndTime());
        }
        List<DeviceData> list = this.list(wrapper);
        return list;
    }
}
